var path = $('body').attr('ctxPath');
var fixtreeBUG=true;

$(function() {
	$('#nav-list li:first').click();
	getRegionTree();
});

$("#helpInfo").on('click',function(){
	if($("#helpShow").is(":hidden")){
	      $("#helpShow").slideDown();   
	}else{
	      $("#helpShow").slideUp();      
	}
})

$('select.chosen-select').chosen({
	width:'100%',
    no_results_text: '没有找到',    // 当检索时没有找到匹配项时显示的提示文本
    disable_search_threshold: 10, // 10 个以下的选择项则不显示检索框
    search_contains: true     // 从任意位置开始检索
});

/**
 * 数据导入按钮
 */
$('#data_import').on('click',function(){
	var companyId = $('#companyId').val();
	if(!companyId){
		layer.alert('请选择公司!');
	}else{
		var data=getListOfChecked();
		if($("#companyId").prop("tagName")=="INPUT"){
			var company=[];
			company.push(companyId);
			data.company=company;
			$('#companyShowInfo').text($('#companyIdText').val());
		}else{
			var  text="";
			$('#companyId').find("option:selected").each(function(i){
				if(i==0){
					text=text+$(this).text();
				}else{
					text=text+"   ,   "+$(this).text();
				}
			});
			$('#companyShowInfo').text(text);
			data.company=companyId;
		}
		var html="";
		var num=0;
		if(data.codeRule.length>0){
			html=html+"<p class='with-padding text-info'>编码规则数据( "+data.codeRule.length+" )条</p>";
			num+=Number(data.codeRule.length);
		}
		if(data.container.length>0){
			html=html+"<p class='with-padding text-info'>容器模板数据( "+data.container.length+" )条</p>";
			num+=Number(data.container.length);
		}
		if(data.transport.length>0){
			html=html+"<p class='with-padding text-info'>运输方式数据( "+data.transport.length+" )条</p>";
			num+=Number(data.transport.length);
		}
		if(data.region.length>0){
			html=html+"<p class='with-padding text-info'>区域数据( "+data.region.length+" )条</p>";
			num+=Number(data.region.length);
		}
		if(data.postion.length>0){
			html=html+"<p class='with-padding text-info'>位置数据( "+data.postion.length+" )条</p>";
			num+=Number(data.postion.length);
		}
		if(data.plan.length>0){
			html=html+"<p class='with-padding text-info'>计划模版数据( "+data.plan.length+" )条</p>";
			num+=Number(data.plan.length);
		}
		$('#dataListShowInfo').html(html);
		$('#num').text(num);
		if(num==0){
			layer.alert("请至少选择一条数据!");
			return;
		}
		$('#dataListShowModal').modal({keyboard:false,show: true});
		$('#dataListShowOkBtn').on('click',data,function(e){
			$('#dataListShowModal').modal('hide');
			var loading =layer.load(1,{//layer加载动画
				shade: [0.5,'#f2f2f2'] //0.5透明度的灰色背景
			});
			$.ajax({
				type:'POST',
				url:path + '/init/data/import?_t='+new Date().getTime(),
				data : JSON.stringify(e.data),
				dataType:'JSON',
				traditional:true,
				contentType: "application/json; charset=utf-8",
				success:function(res){
					if(res.state){
						layer.close(loading);
						layer.alert("导入成功!");
					}else{
						layer.close(loading);
						layer.alert(res.msg);
					}
				},
				error:function(res){
					layer.close(loading);
					layer.alert('网络异常');
				},
				complete:function(res){
					layer.close(loading);
				}
			});
			
		});
	}
});


/**
 * 模板公司的专用功能
 */
$('#init').on('click',function(){
	var companyId = $('#stencilCompanyId').val();
	if(!companyId){
		layer.alert('网络错误,请刷新页面后再试!');
	}else{
	    layer.confirm('该操作会将模板公司的基础数据全部删除,并且重置为系统默认的模板公司的初始状态,且删除操作不可逆!',{
		  title: '您确认要进行数据重置操作嘛？',
		  btn: ['确定','取消'] //按钮
		}, function(){
			var loading =layer.load(1,{//layer加载动画
				shade: [0.5,'#f2f2f2'] //0.5透明度的灰色背景
			});
			$.ajax({
				type:'POST',
				url:path + '/init/generate?_t='+new Date().getTime(),
				data:{'companyId':companyId},
				contentType:"application/json; charset=utf-8",
				dataType: "JSON",
				success:function(data){
					if(data.state){
						layer.close(loading);
						layer.alert(data.msg);
					}else{
						layer.close(loading);
						layer.alert(data.msg);
					}
				},
				error:function(data){
					layer.close(loading);
					layer.alert('网络异常');
				}
			});
		}, function(){
		  layer.msg('用户取消操作', {
		    time: 2000//2s后自动关闭
		  });
		}); 
	}
});


$("#nav-list li:not(.active)").on('click',function(){
	$("#nav-list li.active").removeClass("active");
	$(this).addClass("active");
	$("#nav-body .show").removeClass("show");
	$("#nav-body #"+$(this).children("a").attr("data-type")).addClass("show");
	if($(this).children("a").attr("data-type")=="region"){
		$(".regis-left-text").text("正在加载中请稍后.....");
		if($(".regis-left-text").attr("data-load")=="0"){
			getRegionTree();
		}else{
			$(".regis-left-text").text("");
			
		}
	}
});




$(".table thead :checkbox").on('change',function(){
	if($(this).is(':checked')){
		$(this).parents("thead").next("tbody").find(":checkbox").prop("checked",true);
	}else{
		$(this).parents("thead").next("tbody").find(":checkbox").prop("checked",false);
	}
});


$("#getPostions").on('click',function(){
	$(".regis-right-text").text("");
	var data=getRegionTreeOfChecked();
	if(data.length==0){
		layer.alert('请先选择区域数据!');
		return;
	}
	$("#postion .table-responsive").removeClass("hide");
	$.ajax({
		type:'POST',
		url:path + '/init/getPostions?_t='+new Date().getTime(),
		data:{'codeList':data},
		dataType:'JSON',
		traditional: true,
		success:function(data){
			if(data.state){
				
				$("#getPostions").attr("disabled","disabled");
				$("#postion  .table thead>tr :checkbox").removeAttr("disabled");
				$("#clearPostions").removeAttr("disabled");
				var html="";
				var positionList =data.positions;
				for (var i = 0; i < positionList.length; i++) {
					html=html+"<tr data-id='"+positionList[i].id+"'><td><input type='checkbox'></td><td>"+positionList[i].positionName+"</td></tr>";
				}
				$(".postion .table-responsive table tbody").append(html);
				$("#regis-left-Mask").addClass("regis-left-Mask");
			}else{
				$(".regis-right-text").text(data.msg);
			}
		},error:function(data){
			$(".regis-right-text").text("网络异常,请刷新页面后再试!");
		}
	});
});

$("#clearPostions").on('click',function(){
	$(".regis-right-text").text("等待左侧区域数据选择");
	$("#postion .table-responsive").addClass("hide");
	$("#postion .table-responsive table tbody").empty();
	$("#postion .table thead>tr>th :checkbox").prop("checked",false);
	$("#getPostions").removeAttr("disabled");
	$(this).attr("disabled","disabled");
	$("#postion  .table thead>tr :checkbox").attr("disabled","disabled");;
	$("#regis-left-Mask").removeClass("regis-left-Mask");
	
});


//zTree属性设置
var setting = {
		callback: {
			//onCheck: zTreeOnCheck
		},
		check: {
			enable: true
		},
        view: {
        	showIcon: true,
			showLine: true,
			selectedMulti: false
        },
        data: {
        	key: {
    			name: "menuName"
    		},
            simpleData: {
                enable: true,
                idKey: "code",
    			pIdKey: "parentCode",
    			rootPId: 0
            }
        }
    };


function getRegionTree(){
	$("#postion .table-responsive").addClass("hide");
	$.post(path +'/init/regionTree?_t='+new Date().getTime(),function(data){
		if(data.flag){
			$(".regis-left-text").text("");
			$(".regis-left-text").attr("data-load","1");
			var treeData=data.obj;
			$.fn.zTree.init($("#menuTree"),setting,treeData);
			var treeObj = $.fn.zTree.getZTreeObj("menuTree");
			treeObj.expandAll(true);
		}else{
			$(".regis-left-text").text(data.obj);
			fixtreeBUG=false;
		}
	});
}



//获取选择的树状节点
function getRegionTreeOfChecked(){
	var nodes = $.fn.zTree.getZTreeObj("menuTree").getCheckedNodes();
	var arrList =[];
	if(nodes.length!=0){
		for(var i = 0 ; i < nodes.length ; i++ ){
			arrList.push(nodes[i].code);
		} 
	}
	return arrList;
}

//获取用户选择的数据
function getListOfChecked(){
	var data={};
	
	var codeRule = [];
	$("#codeRule .table tbody").find(":checkbox:checked").each(function(i){
		codeRule.push($(this).parents("tr").attr("data-id"));
    });
	data.codeRule=codeRule;
	
	var container = [];
	$("#container .table tbody").find(":checkbox:checked").each(function(i){
		container.push($(this).parents("tr").attr("data-id"));
    });
	data.container=container;
	
	var transport = [];
	$("#transport .table tbody").find(":checkbox:checked").each(function(i){
		transport.push($(this).parents("tr").attr("data-id"));
    });
	data.transport=transport;
	
	var region = [];
	if(fixtreeBUG){
		region=getRegionTreeOfChecked();
		data.region=region;
	}
	var postion = [];
	$("#postion .table tbody").find(":checkbox:checked").each(function(i){
		postion.push($(this).parents("tr").attr("data-id"));
    });
	data.postion=postion;

	var plan = [];
	$("#plan .table tbody").find(":checkbox:checked").each(function(i){
		plan.push($(this).parents("tr").attr("data-id"));
    });
	data.plan=plan;
	return data;
	
}

	